package com.shanghaionstar.mro;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.onstar.cn.api.ThirdpartyService;
import com.onstar.cn.common.customsdkclass.SafeHandler;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;

import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.core.PermissionCall;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.sqlite.entities.RequestEventReportEntity;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.mag.PlateEngineNumEntity;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.map.OMapView;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.map.common.QueryType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.receive.BrocastReceiveFactory;
import com.onstar.cn.vehicle.result.IResultService;
import com.onstar.cn.vehicle.result.PollingResult;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.VehicleLoadingActivity;
import com.shanghaionstar.activity.webview.handler.CommonWebViewActivity;
import com.shanghaionstar.activity.webview.handler.IWebType;
import com.shanghaionstar.activity.webview.handler.KuaiDaDiWebHandler;
import com.shanghaionstar.activity.webview.handler.WebDataEntity;
import com.shanghaionstar.discover.charge.RemoteCommandUtil;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.enumtype.GaodeType;
import com.shanghaionstar.mro.VechileStatusCheck.MrOVechileDataFragment;
import com.shanghaionstar.mro.VechileStatusCheck.MrOVechileStatusQueryUtil;
import com.shanghaionstar.mro.bean.MrOConstants;
import com.shanghaionstar.mro.bean.MrOOperateType;
import com.shanghaionstar.mro.bean.restrictions.RestrictionsBean;
import com.shanghaionstar.mro.bean.violation.ViolationBean;
import com.shanghaionstar.mro.bean.weather.WeatherBean;
import com.shanghaionstar.mro.iview.IMroView;
import com.shanghaionstar.mro.presenter.MroPresenter;
import com.shanghaionstar.mro.util.MrOAnimationUtil;
import com.shanghaionstar.mro.util.MrOJsonUtil;
import com.shanghaionstar.mro.util.MrOPlayEntity;
import com.shanghaionstar.mro.util.MrOPoiUtil;
import com.shanghaionstar.mro.util.MrOServiceIntroduction;
import com.shanghaionstar.mro.util.MrOWeatherUtil;
import com.shanghaionstar.mro.util.MroGaodeRequestUtil;
import com.shanghaionstar.mro.view.MrOFootLayout;
import com.shanghaionstar.nav.NavActivity;
import com.shanghaionstar.remote.model.RemoteModel;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.OperateReportUtil;
import com.shanghaionstar.utils.RequestUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import rx.Subscription;
import rx.functions.Action1;

/**
 * 小O主界面
 */
@ContentView(R.layout.mro_fragment_container)
public class MrOActivity extends MrOBaseActivity implements IResultService, IMroView {
    public FragmentManager fragmentManager;
    @FindViewById
    private View animation_layout, fragment_container;
    private MrOAnimationUtil animationUtil;
    @FindViewById
    private MrOFootLayout mro_foot;
    // 每次退出activity销毁 mapview, 再次进入需要在resume里初始化
    @FindViewById
    private OMapView mapView;
    private boolean isFinishAnimation = false;
    private OnMroOperationCallbackListener operationCallbackListener;
    private BrocastReceiveFactory poireceiver;

    private HashMap<String, RequestEventReportEntity> mEventReports = new HashMap<>();
    private RequestEventReportEntity mEventReport;

    private String mRemoteMsg;

    private MroPresenter presenter;

    public MrOPoiUtil util;
    public MroGaodeRequestUtil gaodeRequestUtil;

    private Handler mHandler = new SafeHandler<MrOActivity>(this) {
        public void handleMessage(Message msg) {
            MrOActivity activity = reference.get();
            if (activity == null)
                return;
            Bundle bundle = new Bundle();
            String type;
            switch (msg.what) {
                case Constants.LICENSE_PLATE_NUM_NULL:
                    type = (String) msg.obj;
                    bundle.putString("type", type);
                    Bundle msgData = msg.getData();
                    if (msgData != null) {
                        bundle.putString(FinalConfigParams.LICENSE_PLATE_NUM, msgData.getString(FinalConfigParams.LICENSE_PLATE_NUM));
                        bundle.putString(FinalConfigParams.ENGINE_NUM, msgData.getString(FinalConfigParams.ENGINE_NUM));
                    }
                    MrOPlateAndEngineNumberFragment fragment = new MrOPlateAndEngineNumberFragment();
                    fragment.setArguments(bundle);
                    activity.focus(fragment);
                    break;
                case Constants.LOCATION_FAIL:
                    type = (String) msg.obj;
                    activity.focus(activity.locationFailDec(type));
                    break;
            }
        }
    };
    private Subscription mPollingRx;


//     if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
//                            if (context instanceof MrOActivity) {
//                                ((MrOActivity) context).sendRemoteReport(OperateReportUtil.CONTENT_SUCCESS);
//                            }
//                            updateView(pollingResult);
//                        } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
//                            ((MrOActivity) context).sendRemoteReport(OperateReportUtil.CONTENT_FAIL);
//                            updateView(pollingResult);
//                        }

    public void registAllPageAlert() {
        mPollingRx = RxBus.getDefault().toObserverable(Message.class)
                .subscribeOn(getScheduler().backgroundThread())
                .observeOn(getScheduler().mainThread()).subscribe(new Action1<Message>() {
                    @Override
                    public void call(Message msg) {
                        switch (msg.what) {
                            case RxConstants.REMOTE_ERROR:
                                ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                                AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), errorInfo.getDescription());
                                break;
                            case RxConstants.REMOTE_POLLING:
                                RemoteModel model = (RemoteModel) msg.obj;
                                presenter.saveHis(model);
                                break;
                            case RxConstants.REMOTE_WITHOUT_PING:
                                RemoteModel model1 = (RemoteModel) msg.obj;
                                presenter.onAutoSendPin(model1);
                                break;
                            case RxConstants.REMOTE_POLLING_RESULT:
                                PollingResult pollingResult = (PollingResult) msg.obj;
                                RemoteCommandsType remotecommandType = RemoteCommandsType.fromValue(pollingResult.getRequestType());
                                if (pollingResult != null) {
                                    if (pollingResult.getRequestType().equals(RemoteCommandsType.COMMANDS_TBT_ROUTE.value())) {
                                        if (pollingResult.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
                                            AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), getString(R.string.send_to_tbt_success));
                                        } else if (pollingResult.getRequestStatus().equals(RequestStatus.Failure.getStringValue())) {
                                            AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), getString(R.string.send_to_tbt_failed));
                                        }
                                    } else if (presenter.isRemoteCommand(pollingResult.getRequestType())) {
                                        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                                            sendRemoteReport(OperateReportUtil.CONTENT_SUCCESS);
                                            presenter.updateView(pollingResult);
                                        } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                                            sendRemoteReport(OperateReportUtil.CONTENT_FAIL);
                                            presenter.updateView(pollingResult);
                                        }
                                    }
                                }
                                break;
                        }


                    }
                });
        RxSubscriptions.add(mPollingRx);
    }

    public void setupEventEntity() {
        mEventReport = new RequestEventReportEntity();
        mEventReport.setFunctionID(FunctionNameFindId.MrO_FunctionService.getStringValue());
        mEventReport.setStartTimestamp(OperateReportUtil.getDateFromPattern(OperateReportUtil.pattern));
    }

    public void putReport(String type) {
        if (mEventReport != null && !TextUtils.isEmpty(type)) {
            mEventReport.setOperation(type);
            mEventReports.put(type, mEventReport);
        }
    }

    public RequestEventReportEntity getReport(String type) {
        return mEventReports.get(type);
    }

    public void removeReport(String type) {
        mEventReports.remove(type);
    }


    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        presenter = new MroPresenter(getScheduler());
        presenter.setView(this);
        mEventReport = new RequestEventReportEntity();
        util = new MrOPoiUtil();
        gaodeRequestUtil = new MroGaodeRequestUtil();
        registAllPageAlert();
        fragmentManager = getSupportFragmentManager();
//        fragmentManager = getFManager();
        requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, new PermissionCall() {
            @Override
            public void requestSuccess() {
                initMyLocation();
            }

            @Override
            public void refused() {

            }
        });
        operationCallbackListener = new OnMroOperationCallbackListener();
        initView();
//        poireceiver = new BrocastReceiveFactory();
//        registerReceiver(poireceiver, new IntentFilter("BrocastReceiveFactory.poireceiver"));
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                changeFragment(fragmentManager, new MrOHomeFragment(), MrOHomeFragment.class, false);
            }
        });
    }

    /**
     * 发送tbt失败重试toast
     */
    @Override
    public void showAppFrontNavCommandFailToast(final PoiItemInfo poiItemInfo) {

    }

    /**
     * app在后端时候，发送tbt失败提示toast
     *
     * @param poiItemInfo
     */
    @Override
    public void showAppBackNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        ToastView toastView = new ToastView(this);
        toastView.setToastClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAppFrontNavCommandFailToast(poiItemInfo);
            }
        });
    }


    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void hideBodyView() {
        //显示动画图层
        fragment_container.setVisibility(View.GONE);
        animation_layout.setVisibility(View.VISIBLE);
        if (animationUtil != null) {
            animationUtil.checkFigureConfig();
        }
    }

    private void initView() {
        fragment_container.setVisibility(View.VISIBLE);
        animation_layout.setVisibility(View.GONE);
        showBottomMrO(false);
        if (animationUtil == null) {
            animationUtil = new MrOAnimationUtil(animation_layout, this, fragment_container, mro_foot);
        }
        animationUtil.initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        this.setIntent(intent);
    }

    /**
     * if(nocache){
     * if(permit){
     * if(net ok){
     * getLocation();
     * }else {
     * alert(net error)
     * }
     * }else {
     * alert(go to set)
     * }
     * }
     * <p/>
     * if(isGetting){
     * alert(getting)
     * }
     */
    public void initMyLocation() {
        if (mapView == null) {
            mapView = (OMapView) findViewById(R.id.mapView);
        }


        String currentCity = PreferencesUtls.getInstance(this).getString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_CITY_INFO);
        if (!CommonUtil.isNull(currentCity)) {
            util.setCurrCity(currentCity);
        } else {
            if (!CommonUtil.isNull(currentCity)) {
                util.setCurrCity(currentCity);
            } else {
                if (CommonUtil.checkNetWorkState(this)) {
                    requestRunTimePermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new PermissionCall() {
                        @Override
                        public void requestSuccess() {
                            util.getMyLocationFromPhone(mapView, MrOActivity.this);
                        }

                        @Override
                        public void refused() {
                        }
                    });
                } else {
                    AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.mro_net_error), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    });
                }
            }
        }
    }


    public void showBottomMrO(boolean isShow) {
        if (isShow)
            mro_foot.showMrO(true);
        else
            mro_foot.showMrO(false);
    }

    public void showBottomRightBtn(boolean isShow) {
        if (isShow)
            mro_foot.findViewById(R.id.mro_right).setVisibility(View.VISIBLE);
        else
            mro_foot.findViewById(R.id.mro_right).setVisibility(View.INVISIBLE);
    }

    public void showBottomConfirmBtn(boolean isShow) {
        if (isShow)
            mro_foot.showConfirm(true);
        else
            mro_foot.showConfirm(false);
    }


    /**
     * 隐藏输入键盘
     */
    public void hideSoftInput() {
        if (getCurrentFocus() != null && getCurrentFocus().getWindowToken() != null)
            ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }

    public void gotoHelp() {
        changeFragment(fragmentManager, new
                MrOHelpFragment(), MrOHelpFragment.class, true);
        //avoid layout blink because of visibility change
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                animation_layout.setVisibility(View.GONE);
                fragment_container.setVisibility(View.VISIBLE);
                if (animationUtil != null) {
                    animationUtil.stopRecord();
                    animationUtil.initView();
                }
            }
        }, 100);
    }


//    @Override
//    public void onBackPressed() {
//        MrOBaseFragment curFragment = (MrOBaseFragment) getFragment(getCurrentFragmentTag());
//        if (curFragment != null && curFragment.onBackPressed()) {
//            return;
//        }
//        /**
//         * fix multiply clicks to exit MrO page --START
//         */
//        if (curFragment == null) {
//            if (animationUtil != null) {
//                animationUtil.stopRecord();
//            }
//            if (mapView != null) {
//                mapView.onDestroy();
//                mapView = null;
//            }
//            if (animationUtil != null) {
//                animationUtil.release();
//            }
//            setResult(Constants.MAIN_TO_MRO);
//            finish();
//            return;
//        }
//        /**
//         * fix multiply click to exit Mro page  --END
//         */
//
//        if (!(getFragment(getCurrentFragmentTag()) instanceof MrOHomeFragment)) {
//            super.onBackPressed();
//            return;
//        } else {
//            isFinishAnimation = false;
//            if (animationUtil != null) {
//                animationUtil.stopRecord();
//            }
//            if (mapView != null) {
//                mapView.onDestroy();
//                mapView = null;
//            }
//            if (animation_layout.getVisibility() == View.VISIBLE) {
//                initView();
//            } else {
//                if (animationUtil != null) {
//                    animationUtil.release();
//                }
//                setResult(Constants.MAIN_TO_MRO);
//                finish();
//            }
//        }
//    }

    /**
     * they need to back to onstar home page :(
     */
    @Override
    public void onBackPressed() {
        /**
         * help fragment back should work.
         */
        MrOBaseFragment curFragment = (MrOBaseFragment) getFragment(getCurrentFragmentTag());
        if (curFragment instanceof MrOHelpFragment || curFragment instanceof MrOHelpTemplateFragment) {
            super.onBackPressed();
            return;
        }

        if (animationUtil != null) {
            animationUtil.stopRecord();
        }
        if (mapView != null) {
            mapView.onDestroy();
            mapView = null;
        }
        if (animationUtil != null) {
            animationUtil.release();
        }
        setResult(Constants.MAIN_TO_MRO);
        finish();
    }


    public void onConfirmButtonClick() {
        if (getFragment(getCurrentFragmentTag()) instanceof MrOFootLayout.OnFootViewConfirmButtonListener) {
            Fragment fragment = getFragment(getCurrentFragmentTag());
            ((MrOFootLayout.OnFootViewConfirmButtonListener) fragment).onConfirmButtonClick();
        }
    }

    @Override
    public void operationType(MrOOperateType mrOOperateType) {
    }


    public void reRequestGaode(String type, PlateEngineNumEntity entity) {
        if (type.equals(GaodeType.Restrictions.value()) || type.equals(GaodeType.Violation.value())) {
            gaodeRequestUtil.cachePlateEngineNumEntity(entity);
            gaodeRequestUtil.getResult(type, operationCallbackListener, this, mHandler);
            circle();
        }
    }

    /**
     * @param @param position
     * @return void
     * @Title: superBulterClick
     * @Description: 超级管家
     */
    private void superBulterClick(int position) {
        String[] urls = getLinkUrls();
        String[] titles = getResources().getStringArray(R.array.vm_super_bulter_items);
        launchWebCommonView(urls, titles, position);
    }


    protected void launchWebCommonView(String[] urls, String[] titles, int i) {
//        Intent it = new Intent(MrOActivity.this, CommonWebViewActivity.class);
////        String url = EncryptUtil.decryptBase64(mActivity, urls[i]);
//
//        it.putExtra("linkUrl", url);
//        //增加标示，标示只有代驾页面才需要定位请求
//        it.putExtra("requestLocation", url.contains(Constants.DIDIDJ));
//        it.putExtra("isAccept", url.contains("msp"));
//        it.putExtra("topTitle", titles[i]);
//        it.putExtra("canGoBack", true);
//        MrOActivity.this.startActivity(it);
        String url = urls[i];
        WebDataEntity entity = new WebDataEntity();
        entity.setLinkUrl(url);
        entity.setTopTitle(titles[i]);
        entity.setCanGoBack(true);
        if (url.contains(Constants.DIDIDJ)) {
            entity.setWhat(IWebType.TYPE_LOCATION);
            entity.setClzName(KuaiDaDiWebHandler.class.getName());
        } else
            entity.setWhat(IWebType.TYPE_NORMAL);
        CommonWebViewActivity.launchCommonWeb(MrOActivity.this, entity);
    }

    private String[] getLinkUrls() {
        RequestEntity djRequestEntity = getRequestEntity(Constants.DIDIDJ);
        RequestEntity yhouseRequestEntity = getRequestEntity(Constants.YHOUSE);
        RequestEntity golfRequestEntity = getRequestEntity(Constants.YUNGAO);
        String[] urls = {djRequestEntity.getUrl(), yhouseRequestEntity.getUrl(), golfRequestEntity.getUrl()};
        return urls;
    }

    private RequestEntity getRequestEntity(String partnerId) {
        ThirdpartyService service = new ThirdpartyService(Constants.CURRENT_AUTH_URL);
//        DeviceUtil deviceUtil = new DeviceUtil(MrOActivity.this);
//        StringBuilder versionSB = new StringBuilder();
//        versionSB.append(OSType.ANDROID.value());
//        versionSB.append("_");
//        versionSB.append(deviceUtil.getAppVersion());
//        versionSB.append("_");
//        versionSB.append(deviceUtil.getAppVersionCode());
        return service.h5Redirect(partnerId, new RequestEntity());
    }


    public void processListenResult(String msg) {
        log.d("processListenResult:" + msg);
        if (!CommonUtil.isNull(msg)) {
            String oprType = MrOJsonUtil.getOperationType(msg);
            if ("Feedback".equalsIgnoreCase(oprType)) {
                String type = MrOJsonUtil.getValue(msg);
                putReport(type);
                RequestUtil.getInstance().getFeedback(MrOJsonUtil.getContent(msg), operationCallbackListener, this);
                focus(getString(R.string.UC011_MSG004), true);
                showAnswer(msg);
            } else if ("POI".equalsIgnoreCase(oprType)) {//MAPKEY
                String type = MrOJsonUtil.getValue(msg);
                putReport(type);
                sendMroReportImm(msg);
                removeReport(type);
                if ("AroundSearch".equalsIgnoreCase(type) && util.getMyLocation() != null)
//                    NavHolder navHolder = NavHolder.getInstance()
                    util.searchNearBy(MrOJsonUtil.getPOIName(msg), util.getCurrCity(), operationCallbackListener, this);
                else {
                    util.searchByName(MrOJsonUtil.getPOIName(msg), util.getCurrCity(), operationCallbackListener, this);
                }
            } else if ("Command".equalsIgnoreCase(oprType)) {
                String type = MrOJsonUtil.getValue(msg);
                putReport(type);
                sendMroReportImm(msg);
                removeReport(type);
                if ("Weather".equalsIgnoreCase(type)
                        || "Restrictions".equalsIgnoreCase(type)
                        || "Violation".equalsIgnoreCase(type)) {
                    gaodeRequestUtil.getResult(type, operationCallbackListener, this, mHandler);
                }
                //车况类信息查询
                else if ("pressurequery".equalsIgnoreCase(type)
                        || "oilquery".equalsIgnoreCase(type)
                        || "oillifequery".equalsIgnoreCase(type)
                        || "mileagequery".equalsIgnoreCase(type)) {

                    queryPartVehicleStatus(type, msg);
                    sendMroReportImm(msg);
                    removeReport(type);
                } else if ("conditionquery".equalsIgnoreCase(type)) {
                    queryVehicleStatus(type);
                    sendMroReportImm(msg);
                    removeReport(type);
                } else if (oprType.toLowerCase(Locale.CHINA).startsWith("message")) {
                    String introduction = MrOServiceIntroduction.getInstance().getIntroduction(type, this);
                    if (introduction == null) {
                        focus("Unknown Introduction Type", false);
                    } else {
                        focus(introduction, false);
                    }
                    sendMroReportImm(msg);
                    removeReport(type);
                    //车辆位置
                } else if ("position".equalsIgnoreCase(type)) {
                    sendMroReportImm(msg);
                    removeReport(type);
                    MrOPlayEntity entity = new MrOPlayEntity();
                    entity.replyMessage = type;
                    entity.playMessage = msg;
                    entity.needPlay = false;
                    focus(entity);
                } else {
//                    MrORemoteControlUtil.getInstance().remoteControl(type, operationCallbackListener, this);
                    mRemoteMsg = msg;
                    presenter.remoteControl(type, operationCallbackListener);
                }
            } else if ("H5".equalsIgnoreCase(oprType)) {
                sendMroReportImm(msg);
                MrOPlayEntity entity = new MrOPlayEntity();
                entity.replyMessage = "H5";
                entity.playMessage = msg;
                entity.needPlay = false;
                focus(entity);
            } else if (oprType.toLowerCase(Locale.CHINA).startsWith("message")) {
                String type = MrOJsonUtil.getValue(msg);
                sendMroReportImm(msg);
                String introduction = MrOServiceIntroduction.getInstance().getIntroduction(type, this);
                if (introduction == null) {
                    focus("Unknown Introduction Type", false);
                } else {
                    focus(introduction, false);
                }

            } else if (oprType.equalsIgnoreCase("Knowledge")) {
                showAnswer(msg);
            }
        }
    }

    private void showAnswer(String msg) {
        String answer = MrOJsonUtil.getAnswer(msg);
        if (!TextUtils.isEmpty(answer))
            focus(answer, false);
    }

    /**
     * 小O查询车况工具类
     */
    private MrOVechileStatusQueryUtil queryUtil;

    private void queryVehicleStatus(String type) {
        if (queryUtil == null) {
            queryUtil = new MrOVechileStatusQueryUtil(this);
        }
        queryUtil.query(type);
        animationUtil.focus(null);
        animationFinish();
    }

    /**
     * 车况信息查询：里程、胎压、油量、机油寿命、车况
     */
    private void queryPartVehicleStatus(String type, String msg) {
        log.d("type:" + type);
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        bundle.putString("msg", msg);
        MrOVechileDataFragment vechileDataFragment = new MrOVechileDataFragment();
        vechileDataFragment.setArguments(bundle);
        focus(vechileDataFragment);
    }

    private void sendMroReport(String _oprType, String contentSuccess, Context mroActivity) {
        RequestEventReportEntity mEventReport = getReport(_oprType);
        if (mEventReport != null) {
            mEventReport.setEndTimestamp(OperateReportUtil.getDateFromPattern(OperateReportUtil.pattern));
            mEventReport.setOperation(_oprType);
            mEventReport.setContent(contentSuccess);
            OperateReportUtil.operateEventReportFroMro(mEventReport, mroActivity);
            removeReport(_oprType);
        }
    }

    private void sendMroReportImm(String msg) {
        String value = MrOJsonUtil.getValue(msg);
        String status = MrOJsonUtil.getStatus(msg);
        mEventReport.setEndTimestamp(OperateReportUtil.getDateFromPattern(OperateReportUtil.pattern));
        mEventReport.setOperation(value);
        mEventReport.setContent(status);
        OperateReportUtil.operateEventReportFroMro(mEventReport, OnstarApplication.getApplication());
    }

    private void sendMroPOIReportImm(String status) {
        mEventReport.setEndTimestamp(OperateReportUtil.getDateFromPattern(OperateReportUtil.pattern));
        mEventReport.setContent(status);
        OperateReportUtil.operateEventReportFroMro(mEventReport, OnstarApplication.getApplication());
    }

    public void jumpToNav(String title, String msg) {
        Intent it = new Intent(MrOActivity.this, NavActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        bundle.putString("from", MrOActivity.class.getSimpleName());
        it.putExtras(bundle);
        startActivity(it);
    }

    public void sendRemoteReport(String status) {
        if (mRemoteMsg != null) {
            String value = MrOJsonUtil.getValue(mRemoteMsg);
            sendMroReport(value, status, OnstarApplication.getApplication());
        }
    }

    public void jumpToWebview(String msg) {
        String value = MrOJsonUtil.getValue(msg);
        if (value.equalsIgnoreCase("driving")) {
            superBulterClick(0);
        } else if (value.equalsIgnoreCase("ordering")) {
            superBulterClick(1);
        } else if (value.equalsIgnoreCase("golf")) {
            superBulterClick(2);
        }
    }

    private void circle() {
        if (isFinishAnimation) {
            initView();
        }
        hideBodyView();
        animationUtil.circle();
    }

    public void listen() {
        if (util.isLocationing) {
            AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.mro_net_loading));
        } else {
            listen(false);
        }
    }

    public void listen(final boolean isFeedback) {
        requestRunTimePermissions(new String[]{Manifest.permission.RECORD_AUDIO}, new PermissionCall() {
            @Override
            public void requestSuccess() {
                BusinessUtil.sendReportByClickType(MrOActivity.this, FunctionNameFindId.MrO_VoiceService.getStringValue());
                initView();
                mro_foot.setIsFeedback(isFeedback);
                hideBodyView();
                animationUtil.startListen(isFeedback);
            }

            @Override
            public void refused() {
            }
        });
    }

    private void focus(MrOPlayEntity entity) {
        animationUtil.focus(entity);
    }

    private void focus(String replyMessage) {
        MrOPlayEntity entity = new MrOPlayEntity();
        entity.replyMessage = replyMessage;
        entity.needPlay = false;
        animationUtil.focus(entity);
    }

    private void focus(String replyMessage, boolean needPlayTTS) {
        MrOPlayEntity entity = new MrOPlayEntity();
        entity.replyMessage = replyMessage;
        entity.needPlay = needPlayTTS;
        animationUtil.focus(entity);
        animationFinish();
    }

    private void focus(Fragment resultFragment) {
        MrOPlayEntity entity = new MrOPlayEntity();
        entity.playFragment = resultFragment;
        animationUtil.focus(entity);
        animationFinish();
    }

    private void quickShowResult(String message) {
        animationUtil.quickShowResult(message);
        animationFinish();
    }

    public void animationFinish() {
        isFinishAnimation = true;
    }

    @Override
    public void setLoading(boolean isLoading) {

    }

    @Override
    public void onResponseError(OnStarException e) {
        AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning), e.getMessage());
    }

    @Override
    public void onReponseSuccess(Object object) {
        final RemoteModel model = (RemoteModel) object;
        switch (model.getCommandStatus()) {
            case START:
                AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning),
                        model.getAlertMsg(), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                presenter.command(model);
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                focus(getString(R.string.cancel));
                            }
                        });
                break;
            case LOADING:
                setLoading(true);
                break;
            case FINISH:
                AlertDialogUtil.showAlertDialog(MrOActivity.this, getString(R.string.dialog_warning),
                        model.getAlertMsg());
                break;
        }
    }

    @Override
    public Activity onActivity() {
        return MrOActivity.this;
    }

    @Override
    public void showCommandLoading(boolean isShow) {
        if (isShow) {
            startActivity(new Intent(MrOActivity.this, VehicleLoadingActivity.class));
        }
    }

    @Override
    public void showCommandResult(boolean isShow, String result, String time) {
//        操作结果

    }

    @Override
    public void showCommandResult(PollingResult result) {
        RemoteCommandsType commandsType = RemoteCommandsType.fromValue(result.getRequestType());
        if (RequestStatus.Success.getStringValue().equalsIgnoreCase(result.getRequestStatus())) {
            new ToastView(OnstarApplication.getApplication()).showToast(AlertDialogUtil.getResultSystemAlertDialog(OnstarApplication.getApplication(), true, commandsType, null, null));
//                AlertDialogUtil.showResultSystemAlertDialog(context, true, commandsType, null);
            RemoteCommandUtil.playSound(OnstarApplication.getApplication(), commandsType);
        } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(result.getRequestStatus())) {
            if (!CommonUtil.isNull(result.getErrorInfo())) {//如果是一般错误
                new ToastView(OnstarApplication.getApplication()).showToast(AlertDialogUtil.getResultSystemAlertDialog(OnstarApplication.getApplication(), false, commandsType, result.getErrorInfo(), null));
//                    AlertDialogUtil.showResultSystemAlertDialog(context, false, commandsType, result.getErrorInfo());
            } else if (!CommonUtil.isNull(result.getHttpException())) {//如果是网络请求错误
                ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(OnstarApplication.getApplication(), result.getHttpException());
                new ToastView(OnstarApplication.getApplication()).showToast(errorInfo.getMsg());
//                    AlertDialogUtil.showSystemDialogByExceptionCode(context, result.getHttpException(),null);
            }
        }
    }

    @Override
    public void initMapHandler(MapHandler mapHandler) {

    }

    @Override
    public void showPoiToMap(PoiItemInfo poiItemInfo, LocationType locationType) {

    }

    /**
     * @author zengshuai shi
     * @ClassName: OnMroOperationCallbackListener
     * @Description: 高德接口返回结果的处理
     * @date 2015年11月6日 下午2:47:59
     */
    public class OnMroOperationCallbackListener {
        public String plateNum;

        public void onGaodeCallbackListener(String result, String type) {
//            Log.i("zk","gaode result="+result.toString());
            if (CommonUtil.isNull(result)) {
                sendMroReport(type, OperateReportUtil.CONTENT_FAIL, OnstarApplication.getApplication());
                if (type.equals(GaodeType.Violation.value())) {
                    focus(getString(R.string.SB008_MSG009));
                } else if (type.equals(GaodeType.Weather.value())) {
                    focus(getString(R.string.SB005_MSG003));
                } else if (type.equals(GaodeType.Restrictions.value())) {
                    focus(getString(R.string.UC004_MSG003));
                } else {
                    focus(getString(R.string.mro_send_command_failed));
                }
            } else {
                sendMroReport(type, OperateReportUtil.CONTENT_SUCCESS, OnstarApplication.getApplication());
                if (type.equals(GaodeType.Weather.value())) {
                    WeatherBean weatherBean = null;
                    weatherBean = GsonHelper.fromJson(result.toString(), WeatherBean.class);
                    String code = weatherBean.getAts().getCode();
                    if (!CommonUtil.isNull(code) && code.equals("1")) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(GaodeType.Weather.value(), weatherBean);
                        MroWeatherFragment weatherFragment = new MroWeatherFragment();
                        weatherFragment.setArguments(bundle);
                        MrOWeatherUtil weatherUtil = new MrOWeatherUtil(MrOActivity.this);
                        String words = weatherUtil.getWeatherMsg(weatherBean);
                        MrOPlayEntity entity = new MrOPlayEntity();
                        entity.playFragment = weatherFragment;
                        entity.playMessage = words;
                        focus(entity);
                    } else {
                        focus(getString(R.string.SB005_MSG003));
                    }
                } else if (type.equals(GaodeType.Restrictions.value())) {
                    RestrictionsBean restrictionsBean = null;
                    Bundle bundle = new Bundle();
                    restrictionsBean = GsonHelper.fromJson(result.toString(), RestrictionsBean.class);
                    boolean isUndefinedError = false;
                    if (!CommonUtil.isNull(restrictionsBean)) {
//                        if (restrictionsBean.getCode() == 0) {
//
//                        } else if (restrictionsBean.getCode() == 40003) {
//                            bundle.putString("type", GaodeType.Restrictions.value());
//                            bundle.putString("bean", "restrictionsBean");
//                            bundle.putSerializable(GaodeType.Violation.value(), restrictionsBean);
//                            MrOPlateAndEngineNumberFragment numberFragment = new MrOPlateAndEngineNumberFragment();
//                            numberFragment.setArguments(bundle);
//                            focus(numberFragment);
//                        } else if (restrictionsBean.getCode() == 40030) {
//                            focus(getString(R.string.mro_not_support_limit));
//                        } else {
//                            isUndefinedError = true;
//                        }
                        StringBuffer sbHint = new StringBuffer();
                        sbHint.append(restrictionsBean.getCityName());
                        sbHint.append(restrictionsBean.getArea());
                        sbHint.append(restrictionsBean.getInfo());
                        if (!CommonUtil.isNull(restrictionsBean.getNumber())) {
                            sbHint.append("\n" + getString(R.string.restrictions_number, restrictionsBean.getNumber()));
                        }
                        if (!CommonUtil.isNull(restrictionsBean.getNumberRule())) {
                            sbHint.append("\n" + getString(R.string.restrictions_rule, restrictionsBean.getNumberRule()));
                        }
                        focus(getString(R.string.UC004_MSG007, plateNum) + "\n" + sbHint.toString());
                        plateNum = null;
                    } else {
                        isUndefinedError = true;
                    }
                    if (isUndefinedError) {
                        focus(getString(R.string.SB008_MSG008));
                    }
                } else if (type.equals(GaodeType.Violation.value())) {
                    Bundle bundle = new Bundle();
                    MroViolationFragment violationFragment = new MroViolationFragment();
                    ViolationBean violationBean = GsonHelper.fromJson(
                            result.toString(), ViolationBean.class);
                    bundle.putSerializable(GaodeType.Violation.value(), violationBean);
                    bundle.putString("violations", result.toString());
                    bundle.putString("code", "1");
                    bundle.putString(FinalConfigParams.LICENSE_PLATE_NUM, plateNum);
                    plateNum = null;
                    violationFragment.setArguments(bundle);
//                            String words = "";
//                            if (!CommonUtil.isNull(violationBean.getAts().getViolations())) {
//                                words = getString(R.string.SB008_MSG001);
//                            }
                    MrOPlayEntity entity = new MrOPlayEntity();
                    entity.playFragment = violationFragment;
                    focus(entity);
                }
            }

        }

        public void onGaodeCallbakError(String result, String type) {
            sendMroReport(type, OperateReportUtil.CONTENT_FAIL, OnstarApplication.getApplication());
            if (CommonUtil.isNull(result)) {
                if (type.equals(GaodeType.Violation.value())) {
                    focus(getString(R.string.SB008_MSG009));
                    BusinessUtil.sendReportByClickType(MrOActivity.this, FunctionNameFindId.Violationcheckfailedreport.getStringValue());
                } else if (type.equals(GaodeType.Weather.value())) {
                    focus(getString(R.string.SB005_MSG003));
                } else if (type.equals(GaodeType.Restrictions.value())) {
                    focus(getString(R.string.UC004_MSG003));
                } else {
                    focus(getString(R.string.mro_send_command_failed));
                }
            } else {
                if (result.equalsIgnoreCase(MrOConstants.MO1004) || result.equalsIgnoreCase(MrOConstants.MO1005) || result.equalsIgnoreCase(MrOConstants.MO1006)) {
                    Bundle bundle = new Bundle();
                    bundle.putString("type", GaodeType.Violation.value());
                    bundle.putString("bean", "violationBean");
                    MrOPlateAndEngineNumberFragment numberFragment = new MrOPlateAndEngineNumberFragment();
                    numberFragment.setArguments(bundle);
                    focus(numberFragment);
                } else {
                    focus(result);
                }
            }
        }

        public void onPOICallbackListener(List<PoiItemInfo> searchResultList, String keyPlace, QueryType type) {
            if (type == null) {
                sendMroPOIReportImm(OperateReportUtil.CONTENT_FAIL);
                focus(getString(R.string.poi_networkerror_notsearch), false);
                return;
            }
            sendMroPOIReportImm(OperateReportUtil.CONTENT_SUCCESS);
            if (searchResultList == null || searchResultList.size() == 0) {
                focus(getString(R.string.UC014_MSG006), false);
            } else {
                MrOPoiFragment poiFragment = MrOPoiFragment.newInstance(keyPlace);
                poiFragment.setSearchResultList(searchResultList);
                String words = null;
                if (type == QueryType.KEY_WORD) {
                    words = getString(R.string.UC014_MSG004);
                } else {
                    words = getString(R.string.mro_search_the_following_results);
                }
                poiFragment.setHintWords(words);
                MrOPlayEntity entity = new MrOPlayEntity();
                entity.playFragment = poiFragment;
                entity.playMessage = words;
                focus(entity);
            }
        }

        public void onRemoteControlCallbackListener(boolean isNeedFocus, String message) {
//            if(mRemoteMsg != null && isNeedFocus)
//                sendRemoteReport(OperateReportUtil.CONTENT_FAIL);
            if (isNeedFocus) {
                focus(message, false);
            } else {
                quickShowResult(message);
            }
        }

        public void onRemoteControlCallbackListener(Fragment fragment) {
            focus(fragment);
        }

        public void onFeedbackCallbackListener(boolean isSuccess) {
            //no need to deal feedback response
        }
    }

    private String locationFailDec(String type) {
        String dec = "";
        if (type.equals(GaodeType.Weather.value())) {
            dec = getString(R.string.SB005_MSG003);
        } else if (type.equals(GaodeType.Restrictions.value())) {
            dec = getString(R.string.UC004_MSG003);
        } else if (type.equals(GaodeType.Violation.value())) {
            dec = getString(R.string.SB008_MSG009);
        }
        return dec;

    }


    /**
     * (non-Javadoc)
     * <p>Title: onResult</p>
     * <p>Description: </p>
     *
     * @param result
     * @see com.onstar.cn.vehicle.result.IResultService#onResult(com.onstar.cn.vehicle.result.PollingResult)
     */
    @Override
    public void onResult(PollingResult result) {
        if (result != null) {
            if (result.getRequestType().equals(RemoteCommandsType.COMMANDS_TBT_ROUTE.value())) {
                if (result.getRequestStatus().equals(RequestStatus.Success.getStringValue())) {
                    AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.send_to_tbt_success));
                } else if (result.getRequestStatus().equals(RequestStatus.Failure.getStringValue())) {
                    AlertDialogUtil.showAlertDialog(this, getString(R.string.dialog_warning), getString(R.string.send_to_tbt_failed));
                }
            }
        }
    }


    /**
     * (non-Javadoc)
     * <p>Title: onDestroy</p>
     * <p>Description: </p>
     *
     * @see android.support.v4.app.FragmentActivity#onDestroy()
     */
    @Override
    protected void onDestroy() {
        OnstarApplication.getApplication().setMroForeground(false);
        super.onDestroy();
        RxSubscriptions.remove(mPollingRx);
        if (animationUtil != null) {
            animationUtil.release();
        }
        PreferencesUtls.getInstance(this).putString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_CITY_INFO, "");
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
//        try {
//            unregisterReceiver(poireceiver);
//        } catch (Exception e) {
//        }
        presenter.unRegisterSubscriber();
        util = null;
        gaodeRequestUtil = null;
        if (fragmentManager != null) {
            fragmentManager.getFragments().clear();
        }
    }


}
